package cn.fz.difydemo01.controller.dify;

import cn.fz.difydemo01.domain.vo.StreamResponse;
import cn.fz.difydemo01.service.DifyService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@Slf4j
@RestController
@RequestMapping("dify/demo")
@RequiredArgsConstructor
public class DemoController {
    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }

    private final DifyService difyService;

    @GetMapping(value = "chat/messages2", produces = "text/event-stream")
    public Flux<String> chatMessages2(
            @RequestParam(value = "query", required = true) String query,
            @RequestParam(value = "userName", required = true) String userName,
            @RequestParam(value = "conversationId", required = false) String conversationId,
            HttpServletResponse httpServletResponse){
        httpServletResponse.setCharacterEncoding("UTF-8");
        return difyService.streamingMessage2(query, conversationId, userName);
    }

    @GetMapping(value = "chat/messages", produces = "text/event-stream")
    public Flux<StreamResponse> chatMessages(
            @RequestParam(value = "query", required = true) String query,
            @RequestParam(value = "userName", required = true) String userName,
            @RequestParam(value = "conversationId", required = false) String conversationId,
            HttpServletResponse httpServletResponse){
        httpServletResponse.setCharacterEncoding("UTF-8");
        return difyService.streamingMessage(query, conversationId, userName)
                .doOnNext(response->{
                    log.info("流式结果：{}" , response.toString());
                    //workflow_finished节点可以获取完整答案，进行你的逻辑处理
                    if (response.getEvent().equals("workflow_finished")) {
                        log.info("进入workflow_finished阶段");
                        String answer = response.getData().getOutputs().getAnswer();//完整答案
                    }
                    //message_end结束节点，进行你的逻辑处理
                    if (response.getEvent().equals("message_end")) {
                        log.info("进入message_end");
                    }
                });
    }
}
